package com.wayz.service;

import com.wayz.constants.CRoleStatus;
import com.wayz.constants.CRoleType;
import com.wayz.entity.pojo.role.DRoleSaas;
import com.wayz.entity.vo.role.RoleSaasVo;
import com.wayz.exception.WayzException;
import com.wayz.mapper.DRoleSaasDAO;
import com.wayz.mapper.DUserSaasDAO;
import com.wayz.redis.BeanIdKeyEnum;
import com.wayz.redis.RedisUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import javax.annotation.Resource;
import java.util.List;

/**
 * @className: RoleSaasServiceImpl
 * @description: <一句话功能简述> <功能详细描述>
 * @author wade.liu@wayz.ai
 * @date: 2019/6/26
 */
@Service(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class RoleSaasServiceImpl implements RoleSaasService {

	private static final String SAAS_ROLE_VERSION_NAME = "超级管理员";

	/** DAO相关 */
	/** saas角色 */
	@Resource(name = "dRoleSaasDao")
	private DRoleSaasDAO dRoleSaasDao;
	/** saas用户 */
	@Resource(name = "dUserSaasDAO")
	private DUserSaasDAO dUserSaasDAO;

	/** 缓存相关 */
	@Resource(name = "redisUtils")
	private RedisUtils redisUtils;

	/**
	 * 创建saas版本管理员角色
	 * 
	 * @param description
	 * @return
	 */
	@Override
	public Long createVersionRole(String description) throws WayzException {
		// 写入mysql数据库
		RoleSaasVo dRoleSaasCreate = this.insertRoleSaas(description);
		return dRoleSaasCreate.getId();
	}

	/**
	 * 写入mysql数据
	 * 
	 * @param description
	 * @return
	 */
	private RoleSaasVo insertRoleSaas(String description) {
		DRoleSaas dRoleSaasCreate = new DRoleSaas();
		dRoleSaasCreate.setCompanyId(0L);
		dRoleSaasCreate.setId(redisUtils.incrBy(BeanIdKeyEnum.ROLE_SAAS.getKey(), RedisUtils.STEP_SIZE));
		dRoleSaasCreate.setDescription(description);
		dRoleSaasCreate.setIsDeleted(false);
		dRoleSaasCreate.setStatus(CRoleStatus.ENABLE.getValue());
		dRoleSaasCreate.setName(SAAS_ROLE_VERSION_NAME);
		dRoleSaasCreate.setType(CRoleType.VERSION_ADMIN.getValue());
		dRoleSaasDao.create(dRoleSaasCreate);

		RoleSaasVo roleSaasVo = new RoleSaasVo();
		BeanUtils.copyProperties(dRoleSaasCreate, roleSaasVo);

		return roleSaasVo;
	}

	/**
	 * 给saas角色授权
	 * 
	 * @param roleId
	 * @param menuIdList
	 * @return
	 */
	@Override
	public Integer authorityRoleSaaa(Long roleId, List<Long> menuIdList) {
		return dRoleSaasDao.insertRoleMenu(roleId, menuIdList);
	}

	/**
	 * 删除saas版本管理员角色
	 * 
	 * @param
	 * @return
	 */
	@Override
	public void deleteVersionRole(Long roleId) throws WayzException {
		// 获取
		// 检查是否被用
		Boolean exist = dUserSaasDAO.existByRoleId(roleId);
		if (true == exist) {
			throw new WayzException("角色正在被用户使用,不能删除!");
		}
		dRoleSaasDao.delete(roleId);
	}

	/**
	 * 删除角色菜单关联
	 * @param roleId 角色ID
	 */
    @Override
    public void deleteMenuRoleId(Long roleId) throws WayzException {
		dRoleSaasDao.deleteMenuRoleId(roleId);

    }
}
